<template>
  <ContentWrap>
    <!-- 顶部概览统计 -->
    <el-card class="mb-4" shadow="never">
      <el-row :gutter="20" class="statistics-row">
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-icon" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
              <Icon icon="ep:document" />
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ overviewStats.total }}</div>
              <div class="stat-label">总记录数</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-icon" style="background: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);">
              <Icon icon="ep:phone" />
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ overviewStats.connected }}</div>
              <div class="stat-label">已接通</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-icon" style="background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);">
              <Icon icon="ep:warning" />
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ overviewStats.failed }}</div>
              <div class="stat-label">未接通</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-icon" style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);">
              <Icon icon="ep:data-line" />
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ overviewStats.rate }}%</div>
              <div class="stat-label">接通率</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 筛选与搜索区 -->
    <el-card class="mb-4" shadow="never">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="时间筛选">
          <el-select v-model="filterForm.timeRange" placeholder="请选择时间范围" class="w-180px" @change="handleFilter">
            <el-option label="今天" value="today" />
            <el-option label="昨天" value="yesterday" />
            <el-option label="近7天" value="week" />
            <el-option label="近30天" value="month" />
            <el-option label="自定义" value="custom" />
          </el-select>
        </el-form-item>

        <el-form-item v-if="filterForm.timeRange === 'custom'" label="日期范围">
          <el-date-picker
            v-model="filterForm.customDate"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            class="w-240px"
            @change="handleFilter"
          />
        </el-form-item>

        <el-form-item label="通话状态">
          <el-select v-model="filterForm.status" placeholder="请选择状态" class="w-150px" @change="handleFilter">
            <el-option label="全部状态" value="" />
            <el-option label="已接通" value="connected" />
            <el-option label="未接通" value="no_answer" />
            <el-option label="拨号中" value="dialing" />
            <el-option label="失败" value="failed" />
          </el-select>
        </el-form-item>

        <el-form-item label="关键词搜索">
          <el-input
            v-model="filterForm.keyword"
            placeholder="搜索姓名或手机号后4位"
            class="w-220px"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button :icon="Search" @click="handleSearch">搜索</el-button>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" plain :icon="Refresh" @click="handleReset">重置筛选</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 工具栏 -->
    <el-card class="mb-4" shadow="never">
      <div class="toolbar">
        <div class="toolbar-left">
          <el-button type="success" :icon="Download" @click="handleExport" :loading="exportLoading">
            导出记录
          </el-button>
          <el-button :icon="Refresh" @click="handleRefresh" :loading="loading">
            刷新列表
          </el-button>
        </div>
        <div class="toolbar-right">
          <span class="result-count">共 {{ pagination.total }} 条记录</span>
        </div>
      </div>
    </el-card>

    <!-- 通话记录列表 -->
    <el-card shadow="never">
      <el-table
        v-loading="loading"
        :data="recordList"
        stripe
        :row-class-name="tableRowClassName"
      >
        <el-table-column prop="callTime" label="通话时间" width="150" align="left">
          <template #default="{ row }">
            <div class="call-time">
              <Icon icon="ep:clock" class="mr-1" />
              {{ row.callTime }}
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="contactName" label="联系人" width="150" align="center">
          <template #default="{ row }">
            <div class="contact-info">
              <Icon icon="ep:user" class="mr-1" />
              {{ row.contactName || '未知联系人' }}
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="phone" label="电话号码" width="180" align="center">
          <template #default="{ row }">
            <div class="phone-number">
              <Icon icon="ep:phone" class="mr-1" />
              {{ row.phone }}
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="status" label="通话状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="large">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="duration" label="通话时长" width="150" align="center">
          <template #default="{ row }">
            <div class="duration">
              <Icon icon="ep:timer" class="mr-1" />
              {{ formatDuration(row.duration) }}
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="cost" label="通话费用" width="120" align="right" class-name="cost-column">
          <template #default="{ row }">
            <div class="cost">¥{{ row.cost.toFixed(2) }}</div>
          </template>
        </el-table-column>

        <el-table-column label="备注" align="left" min-width="200">
          <template #default="{ row }">
            <div class="remark">{{ row.remark || '-' }}</div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 空状态 -->
      <el-empty
        v-if="!loading && recordList.length === 0"
        description="暂无通话记录"
        :image-size="200"
      >
        <el-button type="primary" @click="handleReset">清空筛选</el-button>
      </el-empty>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.limit"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
  </ContentWrap>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh, Download } from '@element-plus/icons-vue'

defineOptions({ name: 'CallcenterRecord' })

// 状态类型
type CallStatus = 'connected' | 'no_answer' | 'dialing' | 'failed'

// 通话记录接口
interface CallRecord {
  id: number
  callTime: string
  contactName: string
  phone: string
  status: CallStatus
  duration: number
  cost: number
  remark: string
}

// ========== 概览统计 ==========
const overviewStats = ref({
  total: 156,
  connected: 108,
  failed: 48,
  rate: 69.2
})

// ========== 筛选表单 ==========
const filterForm = reactive({
  timeRange: 'today',
  customDate: [],
  status: '',
  keyword: ''
})

// ========== 分页数据 ==========
const pagination = reactive({
  page: 1,
  limit: 20,
  total: 156
})

// ========== 列表数据 ==========
const loading = ref(false)
const exportLoading = ref(false)

// 模拟通话记录数据
const mockRecords: CallRecord[] = [
  { id: 1, callTime: '14:32', contactName: '张三', phone: '*******1234', status: 'connected', duration: 180, cost: 0.6, remark: '客户咨询产品信息' },
  { id: 2, callTime: '14:15', contactName: '李四', phone: '*******5678', status: 'connected', duration: 95, cost: 0.4, remark: '跟进意向客户' },
  { id: 3, callTime: '13:58', contactName: '王五', phone: '*******9012', status: 'no_answer', duration: 0, cost: 0, remark: '未接听' },
  { id: 4, callTime: '13:42', contactName: '赵六', phone: '*******3456', status: 'connected', duration: 320, cost: 1.2, remark: '产品演示' },
  { id: 5, callTime: '13:20', contactName: '孙七', phone: '*******7890', status: 'failed', duration: 0, cost: 0, remark: '号码错误' },
  { id: 6, callTime: '12:55', contactName: '周八', phone: '*******2345', status: 'connected', duration: 156, cost: 0.6, remark: '售后服务' },
  { id: 7, callTime: '12:38', contactName: '吴九', phone: '*******6789', status: 'connected', duration: 210, cost: 0.8, remark: '回访客户' },
  { id: 8, callTime: '12:15', contactName: '', phone: '*******0123', status: 'no_answer', duration: 0, cost: 0, remark: '' },
  { id: 9, callTime: '11:50', contactName: '郑十', phone: '*******4567', status: 'connected', duration: 88, cost: 0.4, remark: '快速咨询' },
  { id: 10, callTime: '11:28', contactName: '钱十一', phone: '*******8901', status: 'connected', duration: 245, cost: 1.0, remark: '详细沟通' },
  { id: 11, callTime: '11:05', contactName: '陈十二', phone: '*******2468', status: 'no_answer', duration: 0, cost: 0, remark: '多次未接' },
  { id: 12, callTime: '10:42', contactName: '刘十三', phone: '*******1357', status: 'connected', duration: 415, cost: 1.6, remark: '深度沟通，客户意向强' },
  { id: 13, callTime: '10:18', contactName: '黄十四', phone: '*******9753', status: 'failed', duration: 0, cost: 0, remark: '系统异常' },
  { id: 14, callTime: '09:55', contactName: '林十五', phone: '*******8642', status: 'connected', duration: 128, cost: 0.5, remark: '预约下次通话' },
  { id: 15, callTime: '09:32', contactName: '杨十六', phone: '*******7531', status: 'connected', duration: 198, cost: 0.8, remark: '确认订单信息' },
]

const recordList = ref<CallRecord[]>([...mockRecords])

// ========== 表格行样式 ==========
const tableRowClassName = ({ rowIndex }: { rowIndex: number }) => {
  return rowIndex % 2 === 0 ? 'even-row' : 'odd-row'
}

// ========== 状态映射 ==========
const getStatusType = (status: CallStatus): 'success' | 'info' | 'warning' | 'danger' => {
  const typeMap: Record<CallStatus, 'success' | 'info' | 'warning' | 'danger'> = {
    connected: 'success',
    no_answer: 'info',
    dialing: 'warning',
    failed: 'danger'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status: CallStatus) => {
  const textMap = {
    connected: '已接通',
    no_answer: '未接通',
    dialing: '拨号中',
    failed: '失败'
  }
  return textMap[status] || '未知'
}

// ========== 时长格式化 ==========
const formatDuration = (seconds: number) => {
  if (seconds === 0) return '0秒'
  const minutes = Math.floor(seconds / 60)
  const secs = seconds % 60
  if (minutes === 0) return `${secs}秒`
  return secs === 0 ? `${minutes}分` : `${minutes}分${secs}秒`
}

// ========== 筛选操作 ==========
const handleFilter = () => {
  loading.value = true
  setTimeout(() => {
    // 模拟筛选逻辑
    let filteredRecords = [...mockRecords]
    
    // 状态筛选
    if (filterForm.status) {
      filteredRecords = filteredRecords.filter(r => r.status === filterForm.status)
    }
    
    // 关键词搜索
    if (filterForm.keyword) {
      filteredRecords = filteredRecords.filter(r => 
        r.contactName.includes(filterForm.keyword) || 
        r.phone.includes(filterForm.keyword)
      )
    }
    
    recordList.value = filteredRecords
    pagination.total = filteredRecords.length
    pagination.page = 1
    
    // 更新统计
    updateOverviewStats(filteredRecords)
    
    loading.value = false
    ElMessage.success('筛选完成')
  }, 500)
}

const handleSearch = () => {
  handleFilter()
}

const handleReset = () => {
  filterForm.timeRange = 'today'
  filterForm.customDate = []
  filterForm.status = ''
  filterForm.keyword = ''
  
  recordList.value = [...mockRecords]
  pagination.total = mockRecords.length
  pagination.page = 1
  
  updateOverviewStats(mockRecords)
  
  ElMessage.success('筛选已重置')
}

// 更新概览统计
const updateOverviewStats = (records: CallRecord[]) => {
  const connected = records.filter(r => r.status === 'connected').length
  overviewStats.value = {
    total: records.length,
    connected: connected,
    failed: records.length - connected,
    rate: records.length > 0 ? Number(((connected / records.length) * 100).toFixed(1)) : 0
  }
}

// ========== 列表操作 ==========
const handleRefresh = () => {
  loading.value = true
  setTimeout(() => {
    recordList.value = [...mockRecords]
    loading.value = false
    ElMessage.success('刷新成功')
  }, 800)
}

const handleExport = () => {
  exportLoading.value = true
  setTimeout(() => {
    exportLoading.value = false
    const currentDate = new Date().toISOString().split('T')[0]
    const filename = `通话记录_${filterForm.timeRange}_${currentDate}.xlsx`
    ElMessage.success(`导出成功：${filename}`)
  }, 1500)
}

// ========== 分页操作 ==========
const handleSizeChange = (size: number) => {
  pagination.limit = size
  pagination.page = 1
  ElMessage.info(`每页显示 ${size} 条`)
}

const handlePageChange = (page: number) => {
  pagination.page = page
  ElMessage.info(`切换到第 ${page} 页`)
}
</script>

<style scoped lang="scss">
// 统计区域
.statistics-row {
  .stat-item {
    display: flex;
    align-items: center;
    padding: 16px;
    background: #fff;
    border-radius: 12px;
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      transform: translateY(-2px);
    }

    .stat-icon {
      width: 56px;
      height: 56px;
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;
      font-size: 28px;
      margin-right: 16px;
      flex-shrink: 0;
    }

    .stat-content {
      flex: 1;

      .stat-value {
        font-size: 28px;
        font-weight: bold;
        color: #303133;
        line-height: 1.2;
        margin-bottom: 4px;
      }

      .stat-label {
        font-size: 14px;
        color: #909399;
      }
    }
  }
}

// 筛选表单
.filter-form {
  margin-bottom: 0;

  :deep(.el-form-item) {
    margin-bottom: 16px;
  }

  :deep(.el-form-item__label) {
    font-weight: 500;
    color: #606266;
  }
}

// 工具栏
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .toolbar-left {
    display: flex;
    gap: 12px;
  }

  .toolbar-right {
    .result-count {
      font-size: 14px;
      color: #606266;
      font-weight: 500;
    }
  }
}

// 表格样式
:deep(.el-table) {
  .even-row {
    background-color: #fafafa;
  }

  .odd-row {
    background-color: #fff;
  }

  tr:hover > td {
    background-color: #f5f7fa !important;
  }

  .call-time {
    display: flex;
    align-items: center;
    color: #606266;
    font-size: 14px;
  }

  .contact-info {
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 500;
    color: #303133;
  }

  .phone-number {
    display: flex;
    align-items: center;
    justify-content: center;
    font-family: 'Courier New', monospace;
    color: #909399;
    font-size: 14px;
  }

  .duration {
    display: flex;
    align-items: center;
    justify-content: center;
    color: #606266;
  }

  .cost {
    font-weight: bold;
    color: #67c23a;
    font-size: 15px;
  }

  .remark {
    color: #909399;
    font-size: 13px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

// 分页容器
.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  padding: 16px 0;
}

// 响应式适配
@media screen and (max-width: 768px) {
  .statistics-row {
    .el-col {
      margin-bottom: 12px;
    }
  }

  .filter-form {
    :deep(.el-form-item) {
      display: block;
      margin-right: 0;
    }
  }

  .toolbar {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;

    .toolbar-left {
      width: 100%;
      flex-direction: column;
    }
  }

  :deep(.el-table) {
    .cost-column {
      display: none;
    }
  }

  .pagination-container {
    :deep(.el-pagination) {
      flex-wrap: wrap;
      justify-content: center;
    }
  }
}
</style>
